package TestThreadPool;

import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.concurrent.*;

/**
 * @Author Mr.Wen
 * @Version 1.0
 * 线程池的六个重要参数
 */
public class ThreadPoolDemo1 {
    public static void main(String[] args) {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
                3,//核心线程数
                5,//最大线程数
                60,//空闲线程最大存活时间
                TimeUnit.SECONDS,//时间单位
                new ArrayBlockingQueue<>(3),//阻塞队列长度
                /*LinkedBlockingQueue 基于链表的队列长度*/
                Executors.defaultThreadFactory(),//创建线程工厂
                new ThreadPoolExecutor.AbortPolicy()//任务的拒绝策略
        );
    }

    @Test
    void test() {
        System.out.println("我的电脑可用线程数:\t" + Runtime.getRuntime().availableProcessors());
        ExecutorService pool = Executors.newFixedThreadPool(3);
        /*阿里巴巴不建议用Executors创建,因为默认用的是LinkedBlockingQueue无界阻塞队列允许大量线程堆积,容易造成OOM*/
        /*对于SingleThreadPool同理*/
        /*对于SynchronousThreadPool设置最大允许Integer.MAX_VALUE线程数量,可能导致创建大量线程导致OOM*/
        Future<Integer> future = pool.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return 1;
            }
        });
        try {
            Integer integer = future.get();
            System.out.println("integer = " + integer);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        pool.shutdown();
    }
}
